

package com.gs.common.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.*;

/**
 * 转换工具类
 *
 * @author Mark sunlightcs@gmail.com
 */
public class ConvertUtils {

    private static Logger logger = LoggerFactory.getLogger(ConvertUtils.class);

    public static <T> T sourceToTarget(Object source, Class<T> target){
        if(source == null){
            return null;
        }
        T targetObject = null;
        try {
            targetObject = target.newInstance();
            BeanUtils.copyProperties(source, targetObject);
        } catch (Exception e) {
            logger.error("convert error ", e);
        }

        return targetObject;
    }

    public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target){
        if(sourceList == null){
            return null;
        }

        List targetList = new ArrayList<>(sourceList.size());
        try {
            for(Object source : sourceList){
                T targetObject = target.newInstance();
                BeanUtils.copyProperties(source, targetObject);
                targetList.add(targetObject);
            }
        }catch (Exception e){
            logger.error("convert error ", e);
        }

        return targetList;
    }

    public static <T> Set<T> sourceToTargetSet(Collection<?> sourceList, Class<T> target){
        if(sourceList == null){
            return null;
        }

        Set targetSet = new HashSet(sourceList.size());
        try {
            for(Object source : sourceList){
                T targetObject = target.newInstance();
                BeanUtils.copyProperties(source, targetObject);
                targetSet.add(targetObject);
            }
        }catch (Exception e){
            logger.error("convert error ", e);
        }

        return targetSet;
    }

    /**
     * 源对象集合转换目标对象集合
     * @param sourceList 源对象集合
     * @param target 目标对象
     * @param <T> 目标对象类型
     * @param copyOptionMap 属性映射
     * @return
     */
    public static <T, v> List<T> sourceToTarget(Collection<v> sourceList, Class<T> target, Map<String, String> copyOptionMap) {
        // 配置字段映射
        CopyOptions copyOptions = CopyOptions.create();
        copyOptions.setFieldMapping(copyOptionMap);


        if(sourceList == null){
            return null;
        }

        List<T> targetList = new ArrayList<>();
        try {
            for(v source : sourceList) {
                T targetObject = (T) target.newInstance();
                BeanUtil.copyProperties(source, targetObject, copyOptions);
                targetList.add(targetObject);
            }
        }catch (Exception e){
            logger.error("convert error ", e);
        }

        return targetList;
    }
}
